package com.vxdata.common.utils;


import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson2.JSON;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;


public class RSAUtil {


    public static <T> T decrypt(String key, String body, Class<T> clazz) throws Exception {
        RSA rsa = new RSA(key, null);
        byte[] buf = rsa.decrypt(body, KeyType.PrivateKey);
        return JSON.parseObject(new String(buf, StandardCharsets.UTF_8), clazz);
    }

    public static void main(String[] args) throws Exception {
        /*Pattern pattern = Pattern.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[%@&'/^/./!,;=?$\\x22]).{8,16}$");
        System.out.println(pattern.matcher("Abc%12389").find());*/
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        //通过对象 KeyPairGenerator 获取对象KeyPair
        KeyPair keyPair = keyPairGen.generateKeyPair();

        //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        //注意每个系统要生成一次公钥和私钥，公钥发给前端工程师，私钥放在后台配置文件中
        //注意！！！私钥一定要保密不能放入前端文件
        System.out.println("publicKey:" + Base64.getEncoder().encodeToString(publicKey.getEncoded()));
        System.out.println("privateKey:" + Base64.getEncoder().encodeToString(privateKey.getEncoded()));


    }
}
